"""
Copyright 2008 VMware, Inc.  All rights reserved. -- VMware Confidential
"""

import os

from vmis.util.log import getLog

# One of either 'gtk', 'console', or 'null'
TYPE = None
# The single instance of the UI.
instance = None

log = getLog('vmis.ui')


def _testGtk():
   """
   Returns True if Gtk is able to be loaded, otherwise False

   @todo: Check to see if loading gtk twice takes a non-trivial amount
   of time.  If so, consider returning the loaded module instead.
   """
   try:
      # Don't force use of our shipped libraries
      forceShipped = True

      # Try to load GTK libraries with AppLoader.  If it succeeds,
      # import gtk and continue the check.
      import vmispy
      loaded = vmispy.LoadGTK(forceShipped)
      if loaded:
         import gtk
         gtk.init_check()
         del gtk
         log.info("Successfully loaded GTK libraries.")
         return True
      else:
         log.info("Failed to load GTK libraries, falling back to console.")
   except ImportError, e:
      log.error('Unable to load gtk: %s', e)
   except Exception, e:
      log.error('Unable to initialize gtk: %s', e)

   return False

def Initialize(ui):
   """
   Initialize the UI system

   @param ui: name of the ui to use (gtk or console)
   """
   global TYPE

   if ui not in ('gtk', 'console'):
      raise ValueError('ui must be either gtk or console')

   # This imports all public symbols from the specific UI into the
   # current module's global scope.
   if ui == 'gtk' and _testGtk():
      TYPE = 'gtk'
      exec 'from vmis.ui.gui import *' in globals()
   else:
      term = os.environ.get('TERM')

      # We need to make sure that we support curses and our terminal
      # can use hpa.  Otherwise we should default to the dumb terminal.
      if term and term not in ('dumb', 'unknown'):
         try:
            import curses
            curses.setupterm()
            hpa = curses.tigetstr('hpa')
            if hpa is None:
               log.info('Terminal does not support hpa.  Falling back '
                        'on the null terminal type.')
               term = 'dumb'
         except Exception, e:
            log.info('Could not set up curses...  Falling back on null term type.')
            term = 'dumb'

      if not term or term in ('dumb', 'unknown'):
         TYPE = 'null'
         exec 'from vmis.ui.null import *' in globals()
      else:
         TYPE = 'console'
         exec 'from vmis.ui.console import *' in globals()

   log.info('Using UI type %s', TYPE)


class MessageTypes:
   """ Types of messages to show """
   INFO, WARNING, ERROR = range(3)
